package com.example.lib_login.view

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View

class MyTextView(context:Context,attrs:AttributeSet?):View(context, attrs) {
    private var text1 = "我已阅读并同意《服务条款》、《隐私政策》"
    private var text2 = "《天翼账号服务协议》"
    private val mPaint:Paint by lazy {
        Paint().apply {
            isAntiAlias = true
            this.textSize = dp2px(12)
            style = Paint.Style.FILL
            color = Color.WHITE
        }
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)


        //确定宽度
        val widthMode = MeasureSpec.getMode(widthMeasureSpec)
        var widthSize = MeasureSpec.getSize(widthMeasureSpec)

        if(widthMode != MeasureSpec.EXACTLY){
            widthSize = mPaint.measureText(text1).toInt()
        }

        //确定高度
        val heightMode = MeasureSpec.getMode(widthMeasureSpec)
        var heightSize = MeasureSpec.getSize(widthMeasureSpec)

        if(heightMode != MeasureSpec.EXACTLY){
            var fontMetriceInt = mPaint.fontMetricsInt
            heightSize = (fontMetriceInt.bottom-fontMetriceInt.top)*3
        }


        setMeasuredDimension(widthSize,heightSize)
    }



    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val textWidth = mPaint.measureText(text1)
        val mx = width - textWidth/2
        var fontMetriceInt = mPaint.fontMetricsInt
        var ay = (fontMetriceInt.bottom - fontMetriceInt.top)/2 - fontMetriceInt.bottom
        var baseline = height/2f+ay
        mPaint.color = Color.parseColor("#606068")
        canvas.drawText(text1,0,7,0f,baseline,mPaint)
        mPaint.color = Color.parseColor("#5F7AA8")
        canvas.drawText(text1,7,20,mPaint.measureText("我已阅读并同意"),baseline,mPaint)
        canvas.drawText(text2,mPaint.measureText("我已阅读"),baseline+(fontMetriceInt.bottom-fontMetriceInt.top),mPaint)
    }

    private fun dp2px(dp:Int) = resources.displayMetrics.density*dp

}